const util = require('../../utils/util.js');

Page({
  data: {
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    dates: [],
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    weightRecords: [],
    displayRecords: [],
    showChart: true,
    chartData: [],
    bmi: 0,
    bmiStatus: { status: '', color: '' },
    height: 170, // 默认身高
    weight: 60,  // 默认体重
    showAddWeightModal: false,
    selectedDate: '',
    newWeight: '',
    showEditHeightModal: false,
    newHeight: '',
    selectedWeightRecord: null, // 添加选中的体重记录
  },

  onLoad: function () {
    // 初始化日历
    this.initCalendar();
    
    // 加载体重记录
    this.loadWeightRecords();
  },

  onShow: function () {
    // 每次页面显示时重新加载数据
    this.loadWeightRecords();
  },

  // 初始化日历
  initCalendar: function () {
    const dates = util.getMonthDates(this.data.currentYear, this.data.currentMonth);
    this.setData({
      dates
    });
  },

  // 加载体重记录
  loadWeightRecords: function () {
    const weightRecords = wx.getStorageSync('weightRecords') || [];
    const height = wx.getStorageSync('userHeight') || this.data.height;
    
    // 获取最新记录的体重
    const latestRecord = weightRecords.length > 0 
      ? weightRecords[weightRecords.length - 1] 
      : { weight: this.data.weight };
    
    const bmi = util.calculateBMI(latestRecord.weight, height);
    
    // 为日历准备显示记录
    const displayRecords = {};
    weightRecords.forEach(record => {
      displayRecords[record.date] = record.weight;
    });
    
    // 准备图表数据（最近7条记录）
    const recentRecords = weightRecords.slice(-7);
    const chartData = this.generateChartData(recentRecords);
    
    this.setData({
      weightRecords,
      displayRecords,
      chartData,
      height,
      weight: latestRecord.weight,
      bmi,
      bmiStatus: util.getBMIStatus(bmi)
    });
  },

  // 处理日历筛选的数据
  generateChartData: function(weightRecords) {
    // 取最近7条记录
    const recentRecords = weightRecords.slice(-7);
    
    // 格式化数据以便于图表显示
    return recentRecords.map(record => {
      // 仅保留月份和日期部分，例如：03-21
      const dateParts = record.date.split('-');
      const formattedDate = dateParts.length >= 3 ? 
                        dateParts[1] + '/' + dateParts[2] : 
                        record.date;
      
      return {
        date: formattedDate,  // 使用MM/DD格式
        weight: record.weight
      };
    });
  },

  // 切换到上个月
  prevMonth: function () {
    let year = this.data.currentYear;
    let month = this.data.currentMonth - 1;
    
    if (month < 1) {
      year--;
      month = 12;
    }
    
    this.setData({
      currentYear: year,
      currentMonth: month
    });
    
    this.initCalendar();
  },

  // 切换到下个月
  nextMonth: function () {
    let year = this.data.currentYear;
    let month = this.data.currentMonth + 1;
    
    if (month > 12) {
      year++;
      month = 1;
    }
    
    this.setData({
      currentYear: year,
      currentMonth: month
    });
    
    this.initCalendar();
  },

  // 选择日期
  selectDate: function (e) {
    const date = e.currentTarget.dataset.date;
    
    this.setData({
      selectedDate: date,
      showAddWeightModal: true,
      newWeight: this.data.displayRecords[date] ? this.data.displayRecords[date].toString() : ''
    });
  },

  // 隐藏添加体重弹窗
  hideAddWeightModal: function () {
    this.setData({
      showAddWeightModal: false
    });
  },

  // 监听输入体重变化
  onWeightInput: function (e) {
    this.setData({
      newWeight: e.detail.value
    });
  },

  // 添加或修改体重记录
  addWeightRecord: function () {
    const newWeight = parseFloat(this.data.newWeight);
    
    if (isNaN(newWeight) || newWeight <= 0) {
      wx.showToast({
        title: '请输入有效的体重数值',
        icon: 'none'
      });
      return;
    }
    
    const date = this.data.selectedDate;
    const weightRecords = wx.getStorageSync('weightRecords') || [];
    
    // 检查是否已有该日期的记录
    const recordIndex = weightRecords.findIndex(record => record.date === date);
    
    if (recordIndex >= 0) {
      // 更新记录
      weightRecords[recordIndex].weight = newWeight;
    } else {
      // 添加新记录并按日期排序
      weightRecords.push({
        date,
        weight: newWeight
      });
      
      weightRecords.sort((a, b) => new Date(a.date) - new Date(b.date));
    }
    
    // 保存到本地存储
    wx.setStorageSync('weightRecords', weightRecords);
    
    // 隐藏弹窗并刷新数据
    this.setData({
      showAddWeightModal: false
    });
    
    this.loadWeightRecords();
    
    wx.showToast({
      title: '体重记录已保存',
      icon: 'success'
    });
  },

  // 显示修改身高弹窗
  showEditHeightModal: function () {
    this.setData({
      showEditHeightModal: true,
      newHeight: this.data.height.toString()
    });
  },

  // 隐藏修改身高弹窗
  hideEditHeightModal: function () {
    this.setData({
      showEditHeightModal: false
    });
  },

  // 监听输入身高变化
  onHeightInput: function (e) {
    this.setData({
      newHeight: e.detail.value
    });
  },

  // 保存身高
  saveHeight: function () {
    const newHeight = parseInt(this.data.newHeight);
    
    if (isNaN(newHeight) || newHeight <= 0) {
      wx.showToast({
        title: '请输入有效的身高数值',
        icon: 'none'
      });
      return;
    }
    
    // 保存到本地存储
    wx.setStorageSync('userHeight', newHeight);
    
    // 隐藏弹窗并刷新数据
    this.setData({
      showEditHeightModal: false,
      height: newHeight
    });
    
    this.loadWeightRecords();
    
    wx.showToast({
      title: '身高已更新',
      icon: 'success'
    });
  },

  // 切换图表显示
  toggleChart: function () {
    this.setData({
      showChart: !this.data.showChart
    });
  },

  // 选择体重记录
  selectWeightRecord: function(e) {
    const record = e.currentTarget.dataset.record;
    this.setData({
      selectedWeightRecord: record
    });
  },
}); 